package com.zhonggong.jbdc;

import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;

import com.mysql.jdbc.Connection;
import com.mysql.jdbc.Driver;
import com.mysql.jdbc.Statement;

public class JDBCDemo {
	
	String URL = "jdbc:mysql://127.0.0.1:3306/zbh";
	String USER = "root";
	String PASSWORD = "root";
	Connection conn = null;
	Statement st = null;
	ResultSet rs = null;
	
	public void query() throws SQLException
	{
		try {
			DriverManager.registerDriver(new Driver());
			Class.forName("com.mysql.jdbc.Driver");
			conn = (Connection) DriverManager.getConnection(URL, USER, PASSWORD);
			st = (Statement) conn.createStatement();
			rs = st.executeQuery("select u_id,u_name,u_age from student");
			while(rs.next())
			{
				System.out.println(rs.getInt("u_id")+" "+rs.getString("u_name")+" "+rs.getInt("u_age"));
			}
		}catch(ClassNotFoundException e)
		{
			e.printStackTrace();
		}catch(SQLException e)
		{
			e.printStackTrace();
		}finally
		{
				rs.close();
				st.close();
				conn.close();
		}
	}
	
	public void insertData() throws SQLException, ClassNotFoundException {
		DriverManager.registerDriver(new Driver());
		Class.forName("com.mysql.jdbc.Driver");
		conn = (Connection) DriverManager.getConnection(URL, USER, PASSWORD);
		st = (Statement) conn.createStatement();
		
		String sqlString = "insert into student(u_name,u_age) values('zhangsan',38)";
		st.execute(sqlString);
		System.out.println("插入成功!");
		
		st.close();
		conn.close();
	}
	
	
	public void updataData() throws SQLException, ClassNotFoundException {
		DriverManager.registerDriver(new Driver());
		Class.forName("com.mysql.jdbc.Driver");
		conn = (Connection) DriverManager.getConnection(URL, USER, PASSWORD);
		st = (Statement) conn.createStatement();
		
		String sqlString = "update student set u_name='zhangsan' where u_age =38";
		st.execute(sqlString);
		System.out.println("修改成功!");
		
		st.close();
		conn.close();
	}
	
	public void deleteData() throws SQLException, ClassNotFoundException {
		DriverManager.registerDriver(new Driver());
		Class.forName("com.mysql.jdbc.Driver");
		conn = (Connection) DriverManager.getConnection(URL, USER, PASSWORD);
		st = (Statement) conn.createStatement();
		
		String sqlString = "delete from student where u_name='lisi'";
		st.execute(sqlString);
		System.out.println("删除成功!");
		
		st.close();
		conn.close();
	}
	
	public static void main(String[] args) throws SQLException, ClassNotFoundException {
		// TODO Auto-generated method stub
		JDBCDemo jdbc = new JDBCDemo();
		jdbc.query();
//		jdbc.insertData();
//		jdbc.updataData();
//		jdbc.deleteData();
//		jdbc.query();
	}
}


